package web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import web.model.SystemParam;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by jly on 2017/5/16.
 */
@Controller
@RequestMapping("/webUploader")
public class WebUploader {

    @RequestMapping("/upload")
    public void upload(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) {
      /*   String id = request.getQueryString();
        String aa = request.getParameter("id");
        String[] strings = id.split("=");
        Integer resultid = Integer.parseInt(strings[1]);
        System.out.print(id);*/
        String fileResour = null;
        String returnUrl = null;
        //代表系统目录中的间隔符，说白了就是斜线，不过有时候需要双线，目前单个方法测试spe不能输出正确结果
        String spe = System.getProperty("file.separator");
        List<SystemParam> list = new ArrayList<SystemParam>();
        String path = "/fileweb";
        String docbase = "D:\\file";
        // 获取tomcat配置的path和docbase
       /* try {
            list = selfProblemService.gettomcatmsg();
        } catch (NormalException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }*/
        /*if (list != null && list.size() != 0) {
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getSyscode().equals("PATH")) {
                    path = list.get(i).getSysvalue();
                }
                if (list.get(i).getSyscode().equals("DOCBASE")) {
                    docbase = list.get(i).getSysvalue();
                }
            }
        }*/

        for (MultipartFile file : files) {
            if (file.isEmpty())
                continue;
            try {
                InputStream content = file.getInputStream();
                Date date = new Date();
                DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
                DateFormat format_hms = new SimpleDateFormat("HHmmss");
                DateFormat format_year = new SimpleDateFormat("yyyy");
                DateFormat format_month = new SimpleDateFormat("MM");
                DateFormat format_day = new SimpleDateFormat("dd");
                @SuppressWarnings("unused")
                String time = format.format(date);
                String hms = format_hms.format(date);
                String year = format_year.format(date);
                String month = format_month.format(date);
                String day = format_day.format(date);
                File folder = new File(docbase + spe + "tableFile");
                // 如果文件夹不存在则创建
                if (!folder.exists() && !folder.isDirectory()) {

                    folder.mkdir();
                }

                File folder_year = new File(docbase + spe + "tableFile" + spe + year);
                // 如果文件夹不存在则创建
                if (!folder_year.exists() && !folder_year.isDirectory()) {

                    folder_year.mkdir();
                }

                File folder_month = new File(docbase + spe + "tableFile" + spe + year + spe + month);
                // 如果文件夹不存在则创建
                if (!folder_month.exists() && !folder_month.isDirectory()) {
                    folder_month.mkdir();
                }

                File folder_day = new File(docbase + spe + "tableFile" + spe + year + spe + month + spe + day);
                // 如果文件夹不存在则创建
                if (!folder_day.exists() && !folder_day.isDirectory()) {
                    folder_day.mkdir();
                }
                String nowTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
                System.out.println("nowTime=======" + nowTime);
                String fileResour2 = docbase + spe + "tableFile" + spe + year + spe + month + spe + day + spe + hms
                        + "-" + file.getOriginalFilename().replace(" ", "");
                // String[] str = fileResour2.split("-");
                // String file_name = str[1];
                String file_name = fileResour2.substring(fileResour2.lastIndexOf("-") + 1);
                // 截取文件名，不包括后缀
                String str2 = file_name.substring(0, file_name.lastIndexOf("."));
                // String str3 =
                // file_name.substring(file_name.lastIndexOf("."));
                fileResour = docbase + spe + "tableFile" + spe + year + spe + month + spe + day + spe + hms + "-"
                        + file_name.replace(str2, nowTime);
                // System.out.println("file.getOriginalFilename()=======" +
                // file.getOriginalFilename());
                // System.out.println("file_name=======" + file_name);
                returnUrl = path + spe + "tableFile" + spe + year + spe + month + spe + day + spe + hms + "-"
                        + file_name.replace(str2, nowTime);
                // System.out.println("returnUrl=======" + returnUrl);
                // int count = resultReportService.getfilecount(file_name,
                // resultid);
                OutputStream os = new FileOutputStream(fileResour);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = content.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                content.close();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
                String nowtime = df.format(new Date());
				/*
				 * if (count > 0) { return 2; } else {
				 */
               /* if (resultReportService.upload(resultid, returnUrl, file_name, nowtime)) {
                    return 1;
                } else {
                    return 0;
                }*/
                // }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
     //   return 0;
    }
}
